package com.gitee.leijin.rbac.security.config;

import com.gitee.leijin.rbac.config.properties.AuthorizationProperties;
import com.gitee.leijin.rbac.security.AuthFilter;
import com.gitee.leijin.rbac.security.CustomAuthenticationEntryPoint;
import com.gitee.leijin.rbac.security.CustomUserDetailsService;
import com.gitee.leijin.rbac.security.handler.CustomAccessDeniedHandler;
import com.gitee.leijin.rbac.security.handler.LoginAuthenticationFailureHandler;
import com.gitee.leijin.rbac.security.handler.LoginAuthenticationSuccessHandler;
import com.gitee.leijin.rbac.security.handler.SuccessLogoutHandler;
import com.gitee.leijin.rbac.service.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Collections;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler;

    @Resource
    private LoginAuthenticationFailureHandler loginAuthenticationFailureHandler;

    @Resource
    private SuccessLogoutHandler successLogoutHandler;

    @Resource
    private AuthorizationProperties authorizationProperties;

    @Resource
    private CustomUserDetailsService customUserDetailsService;

    @Resource
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Resource
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Resource
    private CacheManager cacheManager;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .cors()
                .configurationSource(corsConfigurationSource())
            .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .formLogin()
                .usernameParameter("userName")
                .passwordParameter("password")
                .loginProcessingUrl("/sys-user/login")
                .successHandler(loginAuthenticationSuccessHandler)
                .failureHandler(loginAuthenticationFailureHandler)
            .and()
                .addFilterBefore(authFilter(), LogoutFilter.class)
            .logout()
                .logoutUrl("/sys-user/logout")
                .addLogoutHandler(successLogoutHandler)
            .and()
            .authorizeRequests()
                .antMatchers(authorizationProperties.getWhiteList().toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest()
                // spel 参数可以传 WebSecurityExpressionRoot 或其父类的字段
                .access("@rbacManager.hasPermission(request)")
            .and()
                .exceptionHandling()
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .accessDeniedHandler(customAccessDeniedHandler)
        ;
    }

    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许的域名
        corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
        // 允许的请求头
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        // 允许的方法 GET POST ...
        corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
        // options 预检请求在客户端缓存时间 单位s
        corsConfiguration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 允许跨域访问的url
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter(cacheManager);
    }

}
